var gBookmarkTree;
var gOK;
var gUrls;

function Startup() {
	initServices();
	initBMService();
	gOK = document.documentElement.getButton('accept');
	gBookmarkTree = document.getElementById('bookmarks-view');
	gBookmarkTree.treeBoxObject.view.selection.select(0);
	gBookmarkTree.focus();
}

function onDblClick() {
	if (!gOK.disabled) {
		document.documentElement.acceptDialog();
	}
}

function updateOK() {
	var selection = gBookmarkTree._selection;
	var ds = gBookmarkTree.tree.database;
	var url;

	gUrls = [];

	for (var i = 0; i<selection.length; ++i) {
		var type = selection.type[i];

		if (type == 'Bookmark' || type == '') {
			url = BookmarksUtils.getProperty(selection.item[i], gNC_NS + 'URL', ds);

			if (url) {
				gUrls.push(url);
			}
    		}
	}

	gOK.disabled = gUrls.length == 0;
}

function onOK(aEvent) {
	var selection = gBookmarkTree._selection;
	var bookmark = selection.item[0].Value;
	var aResource = RDF.GetResource(bookmark);
	var aProperty = RDF.GetResource(gNC_NS + 'URL');

	var newValue = RDF.GetLiteral(window.arguments[0].bookmarklet);
	var oldValue = BMDS.GetTarget(aResource, aProperty, true);

	if (oldValue) {
		oldValue = oldValue.QueryInterface(Components.interfaces.nsIRDFLiteral);
	}

	updateAttribute(aResource, aProperty, oldValue, newValue);
}

function updateAttribute(aResource, aProperty, aOldValue, aNewValue) {
	if ((aOldValue || aNewValue) && aOldValue != aNewValue) {
		if (aOldValue && !aNewValue) {
			BMDS.Unassert(aResource, aProperty, aOldValue);
		} else if (!aOldValue && aNewValue) {
			BMDS.Assert(aResource, aProperty, aNewValue, true);
		} else {
			BMDS.Change(aResource, aProperty, aOldValue, aNewValue);
		}

		return true;
	}

	return false;
}
